package com.xmb.wechat.picasso;

import android.graphics.Bitmap;

import com.squareup.picasso.Transformation;

/**
 * @Author lijiangop
 * @CreateTime 2020/5/11 09:58
 */
public class PicassoPYQPicTransform implements Transformation {

    private int itemWidth;

    public PicassoPYQPicTransform(int itemWidth) {
        this.itemWidth = itemWidth;
    }

    @Override
    public Bitmap transform(Bitmap source) {
        //原图的高宽比
        double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
        //缩放宽高
        int aspectWidth;
        int aspectHeight;
        //缩放图片
        Bitmap scaledBitmap, result;
        if (aspectRatio < 1) {//横图
            //缩放宽度
            aspectWidth = Double.valueOf(itemWidth / aspectRatio).intValue();
            result = Bitmap.createBitmap(Bitmap.createScaledBitmap(source, aspectWidth, itemWidth, false),
                    aspectWidth / 2 - itemWidth / 2, 0, itemWidth, itemWidth, null, false);
        } else {//竖图
            //缩放高度
            aspectHeight = Double.valueOf(itemWidth * aspectRatio).intValue();
            result = Bitmap.createBitmap(Bitmap.createScaledBitmap(source, itemWidth, aspectHeight, false),
                    0, aspectHeight / 2 - itemWidth / 2, itemWidth, itemWidth, null, false);
        }
        //recycle
        if (result != source)
            source.recycle();
        return result;
    }

    @Override
    public String key() {
        return "transformation" + " desiredWidth";
    }
}
